package com.shinhye.mobilelottery.ui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.GlobalParams;
import com.shinhye.mobilelottery.R;
import com.shinhye.mobilelottery.bean.ShoppingCart;
import com.shinhye.mobilelottery.bean.Ticket;
import com.shinhye.mobilelottery.ui.manager.MiddleManager;
import com.shinhye.mobilelottery.ui.manager.TitleManager;
import com.shinhye.mobilelottery.utils.PromptManager;

public class OrderUI extends BaseUI implements OnClickListener{
	private Button addOptional;// 添加自选
	private Button addRandom;// 添加机选
	private ListView shoppingList;// 用户选择信息列表
	private ImageButton shoppingListClear;// 清空购物车
	private TextView notice;// 提示信息
	private Button buy;// 购买
	private ShoppingCart shoppingCart;
	private MyAdapter adapter;
	
	/*
	 三个容器
	 通用三步

	 工作清单
	 ①展示购物车
	 ②添加自选和机选
	 ③清空列表
	 ④提示信息处理（高亮）
	 ⑤购买
	 */
	public OrderUI(Context context) {
		super(context);
	}

	@Override
	protected void onCreate() {
		shoppingCart = ShoppingCart.getInstance();
		View showView = View.inflate(getContext(), R.layout.il_shopping, null);
		
		addOptional = (Button) showView.findViewById(R.id.ii_add_optional);
		addRandom = (Button) showView.findViewById(R.id.ii_add_random);
		shoppingListClear = (ImageButton) showView.findViewById(R.id.ii_shopping_list_clear);
		notice = (TextView) showView.findViewById(R.id.ii_shopping_lottery_notice);
		buy = (Button) showView.findViewById(R.id.ii_lottery_shopping_buy);
		shoppingList = (ListView) showView.findViewById(R.id.ii_shopping_list);

		adapter = new MyAdapter();
		shoppingList.setAdapter(adapter);
		
		setContentView(showView);
	}

	class MyAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return shoppingCart.getTicketBag().size();
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = View.inflate(getContext(), R.layout.il_shopping_row, null);
				ViewHolder holder = new ViewHolder();
				holder.delete = (ImageButton) convertView.findViewById(R.id.ii_shopping_item_delete);
				holder.record = (TextView) convertView.findViewById(R.id.ii_shopping_item_money);
				holder.red = (TextView) convertView.findViewById(R.id.ii_shopping_item_reds);
				holder.blue = (TextView) convertView.findViewById(R.id.ii_shopping_item_blues);
				convertView.setTag(holder);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			Ticket ticket = shoppingCart.getTicketBag().get(position);
			holder.red.setText(ticket.getRedNum());
			holder.blue.setText(ticket.getBlueNum());
			holder.record.setText(ticket.getRecord() + "注");
			holder.delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					shoppingCart.getTicketBag().remove(position);
					adapter.notifyDataSetChanged();
					changeNotice();
				}
			});
			return convertView;
		}
		
		@Override
		public Object getItem(int position) {
			return shoppingCart.getTicketBag().get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
	}
	
	static class ViewHolder {
		ImageButton delete;
		TextView red;
		TextView blue;
		TextView record;
	}
	
	@Override
	protected void setListener() {
		addOptional.setOnClickListener(this);
		addRandom.setOnClickListener(this);
		shoppingListClear.setOnClickListener(this);
		buy.setOnClickListener(this);
	}

	@Override
	public int getId() {
		return ConstantValue.VIEW_SHOPPING;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.ii_add_optional:
			MiddleManager.getInstance().goback();
			break;
		case R.id.ii_add_random:
			
			Random random = new Random();
			ArrayList<Integer> redNum = new ArrayList<Integer>();
			while(redNum.size() < 6) {
				int redpos = random.nextInt(33);
				if(redNum.contains(redpos))
					continue;
				redNum.add(redpos);
			}
			int blueNum = (int) (random.nextDouble() * 16);
			
			Ticket ticket = new Ticket();
			DecimalFormat format = new DecimalFormat("00");
			StringBuffer sb = new StringBuffer();
			for(int num : redNum) {
				String str = format.format(num);
				sb.append(str + " ");
			}
			ticket.setRedNum(sb.toString().trim());
			ticket.setBlueNum(format.format(blueNum));
			ticket.setRecord(1);
			
			shoppingCart.getTicketBag().add(ticket);
			adapter.notifyDataSetChanged();
			
			changeNotice();
			break;
		case R.id.ii_shopping_list_clear:
			shoppingCart.getTicketBag().clear();
			adapter.notifyDataSetChanged();
			
			changeNotice();
			break;
		case R.id.ii_lottery_shopping_buy:
			// 购买
			// 判断：用户是否选择了投注信息
			// 判断：用户登录
			// 判断：余额满足要求
			// 界面跳转到：追期和倍投的设置界面

			// 分支
			// 提示用户，需要投注
			// 提示用户，界面跳转到登录界面
			// 提示用户，界面跳转到充值界面

			if(shoppingCart.getTicketBag().size() > 0) {
				if(GlobalParams.isLogin) {
					if(shoppingCart.getLotteryvalue() <= GlobalParams.money) {
						MiddleManager.getInstance().changeUI(PreBetUI.class, getBundle());
					} else {
						PromptManager.showToast(getContext(), "您的余额不足以支付！请先充值！");
					}
				} else {
					PromptManager.showToast(getContext(), "您还没有登陆！");
					MiddleManager.getInstance().changeUI(UserLoginUI.class, null);
				}
			} else {
				PromptManager.showToast(getContext(), "没有投注信息！");
			}
			break;
		}
	}

	/**
	 * Show the total lottery information.
	 */
	private void changeNotice() {
		int lotterynumber = shoppingCart.getLotterynumber();
		int lotteryvalue = shoppingCart.getLotteryvalue();
		String text = getContext().getResources().getString(R.string.is_shopping_list_notice);
		text = StringUtils.replaceEach(text, new String[]{"NUM", "MONEY"}, new String[]{lotterynumber + "", lotteryvalue + ""});
		notice.setText(Html.fromHtml(text));
	}
	
	@Override
	public void onResume() {
		changeTitle();
		changeNotice();
	}

	private void changeTitle() {
		Bundle bundle = getBundle();
		String issue = "";
		String title = "";
		if(bundle != null) {
			issue = bundle.getString("issue");
		}
		if(TextUtils.isEmpty(issue)) {
			title = "双色球选号";
		} else {
			title = "双色球第" + bundle.getString("issue") + "期选号";
		}
		TitleManager.getInstance().changeTitle(title);
	}
}
